package javacommon.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

// Referenced classes of package org.springframework.web.filter:
//            OncePerRequestFilter

public class CharacterEncodingFilter extends OncePerRequestFilter {
	private String encoding;
	private boolean forceEncoding;
	
	public CharacterEncodingFilter() {
		forceEncoding = false;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public void setForceEncoding(boolean forceEncoding) {
		this.forceEncoding = forceEncoding;
	}

	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if (encoding != null
				&& (forceEncoding || request.getCharacterEncoding() == null)) {
			if(request.getMethod().equals("GET")){
				request = new Request(request);   
			}else{
				request.setCharacterEncoding(encoding);
			}
			if (forceEncoding)
				response.setCharacterEncoding(encoding);
		}
		filterChain.doFilter(request, response);
	}

	
	
	class Request extends HttpServletRequestWrapper {   
		  
        public Request(HttpServletRequest request) {   
            super(request);   
        }   
        /**  
         * 转换由表单读取的数据的内码.  
         * 从 ISO 字符转到 utf-8(或gbk).  
         */  
        public String toChi(String input) {   
            try {   
                   
              byte[] bytes = input.getBytes("ISO-8859-1");   
              return new String(bytes, encoding);   
            }   
            catch (Exception ex) {   
            }   
            return null;   
        }   
  
        /**  
         * Return the HttpServletRequest holded by this object.  
         */  
        private HttpServletRequest getHttpServletRequest()   
        {   
            return (HttpServletRequest)super.getRequest();   
        }   
  
        /**  
         * 读取参数 -- 修正了中文问题.  
         */  
        public String getParameter(String name)   
        {   
            return toChi(getHttpServletRequest().getParameter(name));   
        }   
  
        /**  
         * 读取参数列表 - 修正了中文问题.  
         */  
        public String[] getParameterValues(String name)   
        {   
              String values[] = getHttpServletRequest().getParameterValues(name);   
              if (values != null) {   
                for (int i = 0; i < values.length; i++) {   
                  values[i] = toChi(values[i]);   
                }   
              }   
              return values;   
        }   
    }   
}
